import tkinter as tk
import os
import subprocess
import socket
import threading
import queue
import time
import pickle
from Prxy import proxy

q = queue.Queue()

proxy.setQueue(q)

SERVER = None
CLIENT = None
stopFlag = False
log_text = None



def handle_client(client_socket, client_address):
    print(f"Connection from {client_address}")
    try:
        while True:
            data = client_socket.recv(1024)
            if not data or stopFlag:
                break

            q.put(data)

            print(f"Received data from {client_address}: {data.decode()}")

            #response = "Hello from server"
            #client_socket.sendall(response.encode())

        print(f"Client {client_address} disconnected")
        client_socket.close()
    except Exception as e:
        print("client read stopped")

def start_server():
    HOST = '192.168.1.170'
    PORT = 8888
    global SERVER


    SERVER = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    SERVER.bind((HOST, PORT))
    SERVER.listen(5)
    print(f"Server is listening on {HOST}:{PORT}")
    log_text.insert(tk.END, f"Server is listening on {HOST}:{PORT}")

    accept_thread = threading.Thread(target=acceptSer,args=(SERVER,))
    accept_thread.start()
    """
    while True:
        CLIENT, client_address = SERVER.accept()
        client_thread = threading.Thread(target=handle_client, args=(CLIENT, client_address))
        client_thread.start()
    """
def acceptSer(serv):
    try:
        while True:
            print("access in")
            global CLIENT
            CLIENT, client_address = serv.accept()
            proxy.setClient(CLIENT)
            client_thread = threading.Thread(target=handle_client, args=(CLIENT, client_address))
            client_thread.start()
    except Exception as e:
        print("Server stopped")

def run_child_script_with_object(pyf,obj,logger):
    #exec(open(pyf).read())
    # 使用指定的编码方式打开文件并读取内容
    try:
        with open(pyf, 'r', encoding='utf-8') as file:
            script_content = file.read()

        # 执行读取的内容
        exec(script_content)
        # run(obj,logger)
    except Exception as e:
        print(str(e))

def execute_selected_file(event):
    selected_file = listbox.get(listbox.curselection())  # 获取选中的文件名
    if selected_file.endswith('.py'):  # 仅当文件为Python文件时执行
        log_text.insert(tk.END, f"Executing file: {selected_file}\n")
        #result = subprocess.run(['python', selected_file], capture_output=True, text=True)
        #log_text.insert(tk.END, result.stdout)
        #log_text.insert(tk.END, result.stderr)
        proxy.CLIENT = CLIENT
        proxy.q = q
        thread = threading.Thread(target=run_child_script_with_object, args=(selected_file,proxy,log_text))
        thread.start()
def update_file_list():
    file_list = os.listdir()  # 获取当前目录文件列表
    listbox.delete(0, tk.END)  # 清空列表框
    for file in file_list:
        listbox.insert(tk.END, file)  # 将文件名添加到列表框中

# 创建主窗口
root = tk.Tk()
root.title("Execute Python Files")

# 上部分：按钮
button_frame = tk.Frame(root)
button_frame.pack(side=tk.TOP)

button = tk.Button(button_frame, text="Refresh File List", command=update_file_list)
button.pack()

button1 = tk.Button(button_frame, text="tcp server start", command=start_server)
button1.pack()

# 下部分：左右两部分
bottom_frame = tk.Frame(root)
bottom_frame.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

# 左边：文件列表
listbox = tk.Listbox(bottom_frame)
listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
listbox.bind('<Double-Button-1>', execute_selected_file)  # 双击事件绑定

# 右边：日志文本框
#global log_text
log_text = tk.Text(bottom_frame)
log_text.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

def on_closing():
    print("on_closing")
    stopFlag = True
    if SERVER:
        SERVER.close()
        

    if CLIENT:
        CLIENT.close()
    
    root.destroy()
        

root.protocol("WM_DELETE_WINDOW", on_closing)

# 运行主循环
root.mainloop()


